import React, { useState, useMemo } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  TextField,
  Button,
  Chip,
  IconButton,
  Menu,
  MenuItem,
  FormControl,
  InputLabel,
  Select,
  Grid,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Checkbox,
  Paper,
  Tooltip,
  Switch,
  FormControlLabel,
  Alert,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Divider
} from '@mui/material';
import {
  Search as SearchIcon,
  MoreVert as MoreVertIcon,
  Security as SecurityIcon,
  ExpandMore as ExpandMoreIcon,
  Refresh as RefreshIcon,
  GridView as GridViewIcon,
  List as ListIcon
} from '@mui/icons-material';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { PageHeader } from '@/components/common/PageHeader';
import { permissionService } from '@/services/permissionService';
import { roleService } from '@/services/roleService';
import type { Permission, Role } from '@/types';

interface PermissionMatrixData {
  permission: Permission;
  roles: Record<string, boolean>;
}

const PermissionListPage: React.FC = () => {
  const queryClient = useQueryClient();
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedModule, setSelectedModule] = useState<string>('all');
  const [viewMode, setViewMode] = useState<'list' | 'matrix'>('list');
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);

  // 获取权限列表
  const { data: permissions = [], isLoading: permissionsLoading } = useQuery({
    queryKey: ['permissions'],
    queryFn: () => permissionService.getPermissions({})
  });

  // 获取角色列表
  const { data: roles = [], isLoading: rolesLoading } = useQuery({
    queryKey: ['roles'],
    queryFn: () => roleService.getRoles({})
  });

  // 更新角色权限
  const updateRolePermissionsMutation = useMutation({
    mutationFn: ({ roleId, permissions }: { roleId: string; permissions: string[] }) =>
      roleService.updateRolePermissions(roleId, permissions),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['roles'] });
    }
  });

  // 获取所有模块
  const modules = useMemo(() => {
    const moduleSet = new Set<string>();
    permissions.forEach((permission: Permission) => {
      if (permission.module) {
        moduleSet.add(permission.module);
      }
    });
    return Array.from(moduleSet).sort();
  }, [permissions]);

  // 过滤权限
  const filteredPermissions = useMemo(() => {
    return permissions.filter((permission: Permission) => {
      const matchesSearch = !searchTerm ||
        permission.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        permission.description?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        permission.code.toLowerCase().includes(searchTerm.toLowerCase());
      
      const matchesModule = selectedModule === 'all' || permission.module === selectedModule;
      
      return matchesSearch && matchesModule;
    });
  }, [permissions, searchTerm, selectedModule]);

  // 按模块分组权限
  const groupedPermissions = useMemo(() => {
    const groups: Record<string, Permission[]> = {};
    filteredPermissions.forEach((permission: Permission) => {
      const module = permission.module || '其他';
      if (!groups[module]) {
        groups[module] = [];
      }
      groups[module].push(permission);
    });
    return groups;
  }, [filteredPermissions]);

  // 生成权限矩阵数据
  const matrixData = useMemo(() => {
    return filteredPermissions.map((permission: Permission) => {
      const rolePermissions: Record<string, boolean> = {};
      roles.forEach((role: Role) => {
        rolePermissions[role.id] = role.permissions?.includes(permission.id) || false;
      });
      return {
        permission,
        roles: rolePermissions
      };
    });
  }, [filteredPermissions, roles]);

  // 切换角色权限
  const handlePermissionToggle = (roleId: string, permissionId: string, hasPermission: boolean) => {
    const role = roles.find((r: Role) => r.id === roleId);
    if (!role) return;

    let newPermissions: string[];
    if (hasPermission) {
      // 删除权限
      newPermissions = (role.permissions || []).filter(id => id !== permissionId);
    } else {
      // 添加权限
      newPermissions = [...(role.permissions || []), permissionId];
    }

    updateRolePermissionsMutation.mutate({
      roleId,
      permissions: newPermissions
    });
  };

  const handleMenuClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
  };

  const renderListView = () => (
    <Grid container spacing={2}>
      {Object.entries(groupedPermissions).map(([module, modulePermissions]) => (
        <Grid item xs={12} key={module}>
          <Accordion defaultExpanded>
            <AccordionSummary expandIcon={<ExpandMoreIcon />}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <SecurityIcon color="primary" />
                <Typography variant="h6">{module}</Typography>
                <Chip 
                  label={`${modulePermissions.length} 个权限`} 
                  size="small" 
                  variant="outlined" 
                />
              </Box>
            </AccordionSummary>
            <AccordionDetails>
              <Grid container spacing={2}>
                {modulePermissions.map((permission: Permission) => (
                  <Grid item xs={12} sm={6} md={4} key={permission.id}>
                    <Card variant="outlined">
                      <CardContent>
                        <Typography variant="subtitle2" sx={{ mb: 1 }}>
                          {permission.name}
                        </Typography>
                        <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
                          {permission.description || '无描述'}
                        </Typography>
                        <Chip
                          label={permission.code}
                          size="small"
                          variant="outlined"
                          color="secondary"
                        />
                        <Box sx={{ mt: 1, display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                          {roles
                            .filter((role: Role) => role.permissions?.includes(permission.id))
                            .map((role: Role) => (
                              <Chip
                                key={role.id}
                                label={role.name}
                                size="small"
                                color="primary"
                                variant="filled"
                              />
                            ))}
                        </Box>
                      </CardContent>
                    </Card>
                  </Grid>
                ))}
              </Grid>
            </AccordionDetails>
          </Accordion>
        </Grid>
      ))}
    </Grid>
  );

  const renderMatrixView = () => (
    <Card>
      <CardContent>
        <Typography variant="h6" sx={{ mb: 2 }}>
          权限矩阵 - 角色权限分配
        </Typography>
        <Alert severity="info" sx={{ mb: 2 }}>
          在下表中直接勾选或取消勾选复选框来分配或回收角色权限
        </Alert>
        <TableContainer component={Paper} sx={{ maxHeight: 600 }}>
          <Table stickyHeader size="small">
            <TableHead>
              <TableRow>
                <TableCell sx={{ minWidth: 200, fontWeight: 'bold' }}>权限</TableCell>
                <TableCell sx={{ minWidth: 100, fontWeight: 'bold' }}>模块</TableCell>
                {roles.map((role: Role) => (
                  <TableCell
                    key={role.id}
                    align="center"
                    sx={{ minWidth: 120, fontWeight: 'bold' }}
                  >
                    <Tooltip title={role.description || role.name}>
                      <Box>
                        <Typography variant="caption" display="block">
                          {role.name}
                        </Typography>
                        <Chip
                          label={role.code}
                          size="small"
                          variant="outlined"
                          color={role.status === 'active' ? 'success' : 'default'}
                        />
                      </Box>
                    </Tooltip>
                  </TableCell>
                ))}
              </TableRow>
            </TableHead>
            <TableBody>
              {matrixData.map(({ permission, roles: rolePermissions }: PermissionMatrixData) => (
                <TableRow key={permission.id} hover>
                  <TableCell>
                    <Box>
                      <Typography variant="body2" sx={{ fontWeight: 'medium' }}>
                        {permission.name}
                      </Typography>
                      <Typography variant="caption" color="text.secondary">
                        {permission.code}
                      </Typography>
                    </Box>
                  </TableCell>
                  <TableCell>
                    <Chip
                      label={permission.module || '其他'}
                      size="small"
                      variant="outlined"
                      color="primary"
                    />
                  </TableCell>
                  {roles.map((role: Role) => (
                    <TableCell key={role.id} align="center">
                      <Checkbox
                        checked={rolePermissions[role.id] || false}
                        onChange={(e) => 
                          handlePermissionToggle(
                            role.id, 
                            permission.id, 
                            rolePermissions[role.id]
                          )
                        }
                        disabled={role.isSystem} // 系统角色不允许修改
                        size="small"
                      />
                    </TableCell>
                  ))}
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      </CardContent>
    </Card>
  );

  return (
    <Box sx={{ p: 3 }}>
      <PageHeader
        title="权限管理"
        description="管理系统权限和角色权限分配"
        action={
          <Box sx={{ display: 'flex', gap: 1 }}>
            <FormControlLabel
              control={
                <Switch
                  checked={viewMode === 'matrix'}
                  onChange={(e) => setViewMode(e.target.checked ? 'matrix' : 'list')}
                  size="small"
                />
              }
              label="矩阵视图"
            />
            <Button
              variant="outlined"
              startIcon={viewMode === 'matrix' ? <GridViewIcon /> : <ListIcon />}
              onClick={() => setViewMode(viewMode === 'matrix' ? 'list' : 'matrix')}
            >
              {viewMode === 'matrix' ? '列表视图' : '矩阵视图'}
            </Button>
            <IconButton onClick={handleMenuClick}>
              <MoreVertIcon />
            </IconButton>
            <Menu
              anchorEl={anchorEl}
              open={Boolean(anchorEl)}
              onClose={handleMenuClose}
            >
              <MenuItem onClick={() => {
                queryClient.invalidateQueries({ queryKey: ['permissions'] });
                queryClient.invalidateQueries({ queryKey: ['roles'] });
                handleMenuClose();
              }}>
                <RefreshIcon sx={{ mr: 1 }} />
                刷新数据
              </MenuItem>
            </Menu>
          </Box>
        }
      />

      {/* 搜索和筛选 */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Grid container spacing={2} alignItems="center">
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                placeholder="搜索权限名称、描述或代码..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                InputProps={{
                  startAdornment: <SearchIcon sx={{ color: 'text.secondary', mr: 1 }} />
                }}
              />
            </Grid>
            <Grid item xs={12} md={3}>
              <FormControl fullWidth>
                <InputLabel>模块</InputLabel>
                <Select
                  value={selectedModule}
                  label="模块"
                  onChange={(e) => setSelectedModule(e.target.value as string)}
                >
                  <MenuItem value="all">全部模块</MenuItem>
                  {modules.map(module => (
                    <MenuItem key={module} value={module}>{module}</MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={3}>
              <Typography variant="body2" color="text.secondary">
                共 {filteredPermissions.length} 个权限
              </Typography>
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      {/* 内容区域 */}
      {viewMode === 'list' ? renderListView() : renderMatrixView()}
    </Box>
  );
};

export default PermissionListPage;